package com.zzl.test.resp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Description：模拟jedis
 * Created by 朱正磊 on 2019-09-23 15:04
 */
public class EnjoyRedisClient {

    Socket socket;
    InputStream reader;
    OutputStream writer;

    public EnjoyRedisClient() throws IOException {
        socket = new Socket("127.0.0.1", 6379);
        reader = socket.getInputStream();
        writer = socket.getOutputStream();
    }

    /**
     * description：模拟redis的set指令
     * user 朱正磊
     * time 2019-09-23 15:08
     * @param key
     * @param value
     * @return
     */
    public String set(String key, String value) throws IOException {
        StringBuffer command = new StringBuffer();
        command.append("*3").append("\r\n");
        command.append("$3").append("\r\n");
        command.append("SET").append("\r\n");
        command.append("$").append(key.getBytes().length).append("\r\n");
        command.append(key).append("\r\n");
        command.append("$").append(value.getBytes().length).append("\r\n");
        command.append(value).append("\r\n");

        writer.write(command.toString().getBytes());

        byte[] response = new byte[1024];
        reader.read(response);

        return new String(response);
    }

    /**
     * description：模拟redis的get指令
     * user 朱正磊
     * time 2019-09-23 16:00
     * @param key
     * @return
     * @throws IOException
     */
    public String get(String key) throws IOException {
        StringBuffer command = new StringBuffer();
        command.append("*2").append("\r\n");
        command.append("$3").append("\r\n");
        command.append("GET").append("\r\n");
        command.append("$").append(key.getBytes().length).append("\r\n");
        command.append(key).append("\r\n");

        writer.write(command.toString().getBytes());

        byte[] response = new byte[1024];
        reader.read(response);

        return new String(response);
    }

}
